package summary;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


/**
 * @Author: 海琳琦
 * @Date: 2022/3/16 10:31
 * https://leetcode-cn.com/problems/combination-sum/
 */
public class Title131 {

    List<List<String>> result = new ArrayList<>();
    LinkedList<String> list = new LinkedList<>();

    public List<List<String>> partition(String s) {
        backTracking(s, 0);
        return result;
    }

    private void backTracking(String s, int start) {
        if (start >= s.length()) {
            result.add(new ArrayList<>(list));
            return;
        }
        for (int i = start; i < s.length(); i++) {
            if (!isPalindrome(s, start, i + 1)) {
                continue;
            }
            String subStr = s.substring(start, i + 1);
            list.offer(subStr);
            backTracking(s, i + 1);
            list.removeLast();
        }
    }

    boolean isPalindrome(String s, int i, int j) {
        j--;
        for (; i < j; i++) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
            j--;
        }
        return true;
    }








    public List<List<String>> partition2(String s) {
        List<List<String>> result = new ArrayList<>();
        LinkedList<String> temp = new LinkedList<>();
        backTracking1(result, temp, s, 0);
        return result;
    }

    private void backTracking1(List<List<String>> result, LinkedList<String> temp, String s, int start) {
        if (start == s.length()) {
            result.add(new ArrayList<>(temp));
            return;
        }
        //从start开始
        for (int i = start; i < s.length(); i++) {
            if (isHuiWen(s, start, i)) {
                temp.add(s.substring(start, i + 1));
            }else{
                //不是回文串
                continue;
            }
            backTracking1(result, temp, s, i + 1);
            temp.removeLast();
        }
    }

    /**
     * [start, end]
     * @param s
     * @param start
     * @param end
     * @return
     */
    private boolean isHuiWen(String s, int start, int end) {
        while (start < end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }
            start++;
            end--;
        }
        return true;
    }

    public static void main(String[] args) {

    }
}
